package com.ybkj.daijia.api.driver;

import com.ybkj.daijia.api.RealPeopleCertificationApi;
import com.ybkj.daijia.api.aliyun.certification.RealPeopleCertificationResult;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.api.thirdpardCommon.ThirdPartResult;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.api.util.ImageUtil;
import com.ybkj.daijia.server.event.model.DriverOnlineEvent;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverLogin;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverLoginService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.SuperviceService;
import com.ybkj.daijia.serverUtils.IOUtils;
import com.ybkj.daijia.serverUtils.WebUtils;
import java.io.File;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhyu
 * @date 2019/12/27 15:32
 */
@RestController
@RequestMapping("driver/api/rest")
@Slf4j
public class DriverAccountController {

    @Autowired
    private DriverService driverService;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private RealPeopleCertificationApi<RealPeopleCertificationResult> realPeopleCertificationApi;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private DriverLoginService driverLoginService;
    @Autowired
    private SuperviceService superviceService;

    /**
     * v1.2的司机上线
     * @createdBy zhyu
     * @param employToken
     * @param base64
     * @return
     */
    @ResponseBody
    @RequestMapping("online")
    public ResultTransport online(String employToken, String base64) {
        if (StringUtils.isBlank(employToken) || null == base64) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        float mbMax = 1f;
        boolean shouldCompress = ImageUtil.checkImageBase64Size(base64, mbMax);
        //如果要求前端不能上传太大的图片, 那么这儿可以判断和抛异常了
        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);
        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }
        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }
        Driver driver = driverService.findOne(driverLogin.getDriverId());
        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }
        //帐号被冻结
        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }
        Company company = companyService.findOne(driver.getCompanyId());
        if (driver.getType().equals(Driver.DRIVER_TYPR_PARTTIME)
            && company.getLowestWorkVirtual().doubleValue() != 0
            && driver.getVirtual().doubleValue() < company.getLowestWorkVirtual().doubleValue()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.LOWEST_WORK_VIRTUAL_ERROR);
        }
        // TODO 在司机申请接口添加headPhoto的2M检测.和管理员审核和司机编辑页面对应的接口也添加2M检测和添加压缩,
        String photoName = driver.getPhoto();
        if (StringUtils.isBlank(photoName)) {
            return ResultTransport.getErrorBy(ErrorConstant.ROLE_INFORMATION_IS_INCOMPLETE);
        }

        String photoPath = WebUtils.getBasePath(request) + Driver.DRIVER_PATH + File.separator + photoName;
        int end = photoName.indexOf(".png");
        if (-1 != end) {
            String newNamePath = WebUtils.getBasePath(request) + Driver.DRIVER_PATH + File.separator + photoName.substring(0, end) + ".jpg";
            IOUtils.convertPngToJpg(new File(photoPath), newNamePath);
            driver.setPhone(newNamePath);
            driverService.updateColumnsIfNotNull(driver);
        }
        String srcBase64 = ImageUtil.checkSizeAndConvertToBase64(WebUtils.getBasePath(request) + Driver.DRIVER_PATH + File.separator + photoName, mbMax);
        //爆了413 Request Entity Too Large
        if (shouldCompress) {
            base64 = ImageUtil.useGoogleZoom(base64, mbMax);
        }
        ThirdPartResult<RealPeopleCertificationResult> thirdPartResult = realPeopleCertificationApi.compareTwoHeadPhotoes(null, null, srcBase64, base64);
        boolean checkOk = false;
        if (thirdPartResult.getSuccess()) {
            if (thirdPartResult.getData().isRecommendResult()) {
                checkOk = true;
            }
        }else {
            if (log.isErrorEnabled()) {
                log.error("实人认证 http请求没有返回success消息, photoBase64 == null:{} \n{}", null == srcBase64,thirdPartResult);
            }
        }
        if (!checkOk) {
            return ResultTransport.getErrorBy(ErrorConstant.DRIVER_IS_DISSIMILAR_WITH_HEAD_PHOTO);
        }
        if (driver.getStatus().equals(Driver.DRIVER_OFFLINE)) {
            driver.setStatus(Driver.DRIVER_ONLINE);
            driver.setDutyTime(new Date());
            driverService.online(driver);
            DriverOnlineEvent driverOnlineEvent = new DriverOnlineEvent(driver);
            applicationEventMulticaster.multicastEvent(driverOnlineEvent);
        }
        //上班成功
        ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
        instance.setData(driver.getStatus());
        //驾驶员上线推送监管平台
        superviceService.pushTjyy(driver);
        return instance;
    }

    public static void main(String[] args) {
        String path = "G:\\gitlab\\daijia\\server\\src\\main\\webappupload/driver\\24150c98f0934df6bd4c0c4b386e56ee.jpg";
        File file = new File(path);
        System.out.println(file.exists());
    }
}
